const { logger } = require('../utils/logger');

const errorCodeToStatus = {
    invalid_payload: 400,
    validation_error: 422,
    unauthorized: 401,
    forbidden: 403,
    not_found: 404,
    conflict: 409,
    too_busy: 429,
    rate_limited: 429,
    timeout: 504,
};

function formatErrorResponse(err) {
    const code = err.code || err.error || 'internal_error';
    const status = errorCodeToStatus[code] || 500;
    const response = { error: code };
    if (err.message && err.expose !== false && status < 500) {
        response.message = err.message;
    }
    if (err.details && typeof err.details === 'object') {
        response.details = err.details;
    }
    return { status, body: response };
}

// eslint-disable-next-line no-unused-vars
function errorHandler(err, req, res, next) {
    const { status, body } = formatErrorResponse(err || {});
    logger.error({ err, path: req.path, method: req.method, status }, 'request failed');
    res.status(status).json(body);
}

module.exports = { errorHandler };


